package org.javatribe.calculator.common;

import java.util.function.Consumer;
import java.util.function.Function;

/**
 * Created by Wenxin on 2017/9/15.
 */
public class CallbackImpl implements Callback {

    private BaseFrame baseFrame;

    private Consumer<? super BaseFrame> success;

    private Consumer<? super Exception> failure;

    private Function<BaseFrame, Void> run;

    public CallbackImpl() {
    }

    @Override
    public Callback success(Consumer<? super BaseFrame> success) {
        this.success = success;
        return this;
    }

    @Override
    public Callback failure(Consumer<? super Exception> failure) {
        this.failure = failure;
        return this;
    }

    @Override
    public Callback execute(Function<BaseFrame, Void> run) {
        this.run = run;
        return this;
    }

    @Override
    public void run() {
        try {
            if (run == null) {
                throw new IllegalArgumentException("the run function must be set.");
            }
            run.apply(baseFrame);
            if (success != null) {
                success.accept(baseFrame);
            }
        } catch (Exception e) {
            if (failure != null) {
                failure.accept(e);
            }
        }
    }

}
